<template>
  <BasicDrawer
    v-bind="$attrs"
    showFooter
    @register="channelRegister"
    width="1000"
    :extraScrollHeight="57"
    isAbsolute
    @ok="confirmSubmit"
    @close="drawerReset"
    getContainer=".page-wrapper"
  >
    <template #contentExtra>
      <div class="drawer-tab">
        <template v-for="item in tabObj.tabList" :key="item.key">
          <div
            v-if="item.isShow"
            :class="['tab-item', item.key === tabObj.activeKey ? 'tab-active' : '']"
            @click="tabHandle(item.key)"
          >
            {{ item.tab }}
          </div>
        </template>
        <div class="tab-position global-txt-ellipsis">渠道名称：{{ drawerInfo.channelName || '--' }}</div>
      </div>
    </template>
    <div class="box-drawer">
      <div v-show="tabObj.activeKey === '1'" class="box-product">
        <div class="channel-form">
          <a-form ref="formRef" :colon="false" autocomplete="off" :label-col="{ style: { width: '130px' } }" lableWidth>
            <div class="channel-box">
              <div class="channel-custom">
                <a-form-item label="自定义开关" name="brandSwitch">
                  <a-switch
                    v-model:checked="drawerInfo.record.brandSwitch"
                    :checkedValue="1"
                    :unCheckedValue="0"
                    checked-children="启用"
                    un-checked-children="关闭"
                  />
                </a-form-item>
                <info-circle-outlined class="icon" />
                <span class="describe">注意：仅在开关开启后，此部分的自定义的内容才生效</span>
              </div>
              <div class="title scroll-item">H5链接自定义</div>
              <div class="service" style="margin-bottom: 0">
                <div class="service-btn">
                  <a-form-item label="BPai-H5专属登录链接">
                    <a-input
                      disabled
                      placeholder="点击生成按钮生成链接"
                      v-model:value.trim="drawerInfo.record.loginUrl"
                    >
                    </a-input>
                  </a-form-item>
                  <a-button
                    type="primary"
                    class="btn-link"
                    @click="linkHandle('loginUrl')"
                    :loading="loadingObj.loginUrlLoading"
                  >
                    {{ drawerInfo.record.loginUrl ? '复制链接' : '生成链接' }}
                  </a-button>
                </div>
              </div>
              <div class="title scroll-item">logo自定义</div>
              <div class="uploadLogo">
                <a-form-item name="loginLogo" label="移动端登录页logo">
                  <a-upload
                    name="loginLogo"
                    list-type="picture-card"
                    accept="image/png"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :disabled="mobileloading"
                    :before-upload="beforeUpload"
                    :customRequest="handleMobileRequest"
                  >
                    <template v-if="drawerInfo?.record.loginLogo">
                      <img :src="drawerInfo?.record.loginLogo" alt="移动端登录页logo" :width="335" :height="70" />
                      <close-circle-filled class="file-close" @click.stop="drawerInfo.record.loginLogo = ''" />
                    </template>
                    <div class="inner-info" v-else style="width: 335px; height: 70px">
                      <loading-outlined v-if="mobileloading"></loading-outlined>
                      <upload-outlined v-else></upload-outlined>
                      <div class="ant-upload-text">上传图片</div>
                    </div>
                  </a-upload>
                  <div class="upload-info">
                    <info-circle-outlined class="info-icon" />
                    只支持png格式，1005px*210px
                  </div>
                </a-form-item>
              </div>
              <div class="title scroll-item">H5客服信息</div>
              <div class="service box-desc">
                <div class="uploadLogo uploadCustomer">
                  <a-form-item name="customerQr" label="联系客服二维码">
                    <a-upload
                      name="customerQr"
                      list-type="picture-card"
                      accept="image/png"
                      class="avatar-uploader"
                      :show-upload-list="false"
                      :disabled="customerloading"
                      :before-upload="beforeUpload"
                      :customRequest="handleCustomerRequest"
                    >
                      <template v-if="drawerInfo?.record.customerQr">
                        <img :src="drawerInfo?.record.customerQr" alt="联系客服二维码" :width="126" :height="126" />
                        <close-circle-filled class="file-close" @click.stop="drawerInfo.record.customerQr = ''" />
                      </template>
                      <div class="inner-info" v-else style="width: 126px; height: 126px">
                        <loading-outlined v-if="customerloading"></loading-outlined>
                        <upload-outlined v-else></upload-outlined>
                        <div class="ant-upload-text">上传图片</div>
                      </div>
                    </a-upload>
                    <div class="upload-info">
                      <info-circle-outlined class="info-icon" />
                      只支持png格式，384*384px
                    </div>
                  </a-form-item>
                </div>
              </div>
            </div>
          </a-form>
        </div>
      </div>
      <div v-show="tabObj.activeKey === '2'" v-if="initDataLoading">
        <PackageSet ref="packageSetRef" :operateType="drawerInfo.type" :packageSetData="drawerInfo.record" />
      </div>
    </div>
  </BasicDrawer>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, unref } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { operateActionType } from '@/types/enum'
import { InfoCircleOutlined, UploadOutlined, LoadingOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { cloneDeep, debounce } from 'lodash-es'
import PackageSet from './PackageSet.vue'
import api from '@/api'
import ObsClient from 'esdk-obs-browserjs/src/obs'
import { obsUpAndDownload } from '@/utils/file/obs'
import useClipboard from 'vue-clipboard3'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'

const {
  updateBrandConfig,
  uploadLogo,
  generateChannelLoginUrlOrDownloadUrl,
  getConfigByChannelCode,
  updateSalesConfig
} = api

const userModule = userStore()

const { toClipboard } = useClipboard()

const emit = defineEmits(['operateSuccess', 'register'])

const packageSetRef = ref()

const initDataLoading = ref<boolean>(false)
const mobileloading = ref<boolean>(false)
const customerloading = ref<boolean>(false)
const formRef = ref()

let obsClient: any

const tabObj = reactive({
  activeKey: '1',
  tabList: [
    {
      key: '1',
      tab: '品牌自定义',
      isShow: true
    },
    {
      key: '2',
      tab: '售卖方式',
      isShow: true
    }
  ]
})

const drawerInfo = reactive<any>({
  type: '',
  channelName: '',
  channelNo: '',
  record: {
    brandSwitch: 0,
    customerQr: '',
    cyclePackageVOS: [],
    feeModel: '',
    freeLimit: 0,
    freeTimes: 0,
    loginLogo: '',
    loginUrl: '',
    payQr: '',
    saleSwitch: 0,
    scorePackageVOS: []
  }
})

const loadingObj = reactive({
  loginUrlLoading: false
})

const obsFileName = 'bpaiChannel'
const getObsClient = async () => {
  let res = await uploadLogo({
    dir: `psy-public/${import.meta.env.VITE_OBS_DIR}/UI/${obsFileName}`
  })
  let result = res.result
  obsClient = new ObsClient({
    access_key_id: result.access, // 你的ak
    secret_access_key: result.secret, // 你的sk
    security_token: result.securitytoken,
    server: result.server // 你的endPoint
  })
}
onMounted(async () => {
  await getObsClient()
})
const [channelRegister, { closeDrawer, changeOkLoading, changeLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  drawerInfo.channelName = data.record.channelName || ''
  drawerInfo.channelNo = data.record.channelNo || ''

  tabObj.tabList[0].isShow = userModule.permissionActionList.includes(permissionCodeMap.bpaiChannelBrand)
  tabObj.tabList[1].isShow = userModule.permissionActionList.includes(permissionCodeMap.bpaiChannelSale)

  for (let i = 0; i < tabObj.tabList.length; i++) {
    if (tabObj.tabList[i].isShow) {
      tabObj.activeKey = tabObj.tabList[i].key
      break
    }
  }

  try {
    changeLoading(true)
    initDataLoading.value = false
    let res = await getConfigByChannelCode({
      channelNo: data.record.channelNo
    })
    changeLoading(false)
    drawerInfo.record = res.result || {}
    initDataLoading.value = true
  } catch (error) {
    changeLoading(false)
    initDataLoading.value = true
  }
})

// 链接处理
const linkHandle = async (type: string) => {
  if (type === 'loginUrl') {
    if (drawerInfo.record.loginUrl) {
      await toClipboard(drawerInfo.record.loginUrl)
      message.success('复制链接成功')
    } else {
      try {
        loadingObj.loginUrlLoading = true
        let res = await generateChannelLoginUrlOrDownloadUrl({
          channelCode: drawerInfo.channelNo,
          loginOrDownloadUrlFlag: '4'
        })
        loadingObj.loginUrlLoading = false
        if (res.result) {
          drawerInfo.record.loginUrl = res.result.bpaiH5LoginUrl
        }
      } catch (error) {
        loadingObj.loginUrlLoading = false
      }
    }
  }
}
// tab切换
const tabHandle = (key: string) => {
  tabObj.activeKey = key
}
// 重置信息
const drawerReset = () => {
  changeOkLoading(false)
  changeLoading(false)
  tabObj.activeKey = '1'
  emit('operateSuccess')
}

// 提交数据
const confirmSubmit = async () => {
  try {
    if (tabObj.activeKey === '1') {
      changeOkLoading(true)
      let record = drawerInfo.record
      let reqParam = {
        brandSwitch: record.brandSwitch,
        channelName: drawerInfo.channelName,
        channelNo: drawerInfo.channelNo,
        customerQr: record.customerQr,
        loginLogo: record.loginLogo,
        loginUrl: record.loginUrl
      }
      await updateBrandConfig(reqParam)
      message.success('当前品牌自定义配置成功')
      changeOkLoading(false)
    } else if (tabObj.activeKey === '2') {
      let data = packageSetRef.value.submitData()
      if (data) {
        changeOkLoading(true)
        await updateSalesConfig({
          channelName: drawerInfo.channelName,
          channelNo: drawerInfo.channelNo,
          feeModel: data.feeModel,
          freeLimit: data.freeLimit,
          freeTimes: data.freeTimes,
          packageVOS: data.feeModel === 'CYCLE' ? data.cyclePackageVOS : data.scorePackageVOS,
          payQr: data.payQr,
          saleSwitch: data.saleSwitch
        })
        message.success('当前售卖方式配置成功')
        changeOkLoading(false)
      }
    }
  } catch (error) {
    changeOkLoading(false)
  }
}
// 校验文件格式
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('请上传图片文件')
    return false
  }
  return true
}

// 移动端登录页logo上传obs和下载展示
const handleMobileRequest = async (options: any) => {
  try {
    mobileloading.value = true
    await getObsClient()
    options.obsFileName = obsFileName
    drawerInfo.record.loginLogo = await obsUpAndDownload(obsClient, options)
    mobileloading.value = false
  } catch (error) {
    mobileloading.value = false
  }
}
// H5-联系客服二维码上传obs和下载展示
const handleCustomerRequest = async (options: any) => {
  try {
    customerloading.value = true
    await getObsClient()
    options.obsFileName = obsFileName
    drawerInfo.record.customerQr = await obsUpAndDownload(obsClient, options)
    customerloading.value = false
  } catch (error) {
    customerloading.value = false
  }
}
</script>

<style scoped lang="less">
.box-drawer {
  padding: 8px 8px 0;
  .channel-form,
  .channel-view {
    height: calc(100vh - 320px);
    overflow-y: auto;
  }
}
.drawer-tab {
  border-bottom: 1px solid #e0e1e6;
  margin: 20px 24px 0;
  display: flex;
  align-items: center;
  position: relative;
  .tab-position {
    position: absolute;
    right: 0;
    top: 0;
    font-weight: 600;
    font-size: 14px;
    color: #555d6f;
    line-height: 20px;
    max-width: 500px;
  }
  .tab-item {
    color: #555d6f;
    line-height: 20px;
    margin-left: 40px;
    padding-bottom: 16px;
    position: relative;
    cursor: pointer;
    &.tab-active {
      font-weight: 600;
      color: #4aa353;
      &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 50%;
        width: 40px;
        height: 4px;
        background: #4aa353;
        border-radius: 100px 100px 0 0;
        transform: translateX(-50%);
        z-index: 5;
      }
    }
  }
}
:deep(.scrollbar__wrap) {
  padding: 24px;
}
:deep(.ant-form-item-label) {
  font-weight: 600;
  & > label {
    font-size: 12px;
    color: #192236;
    align-items: center;
  }
}
:deep(.box-desc) {
  margin-top: -16px;
  padding: 0 8px;

  .ant-descriptions-item-label {
    justify-content: end;
    // align-items: center;
    width: 120px;
    font-size: 12px;
    color: #192236;
    font-weight: 600;
  }
  .ant-descriptions-row > th {
    padding-bottom: 6px;
  }
  .ant-descriptions-row > td {
    padding-bottom: 30px;
  }
  .ant-descriptions-row:last-child > td {
    padding-bottom: 0;
  }
  .ant-descriptions-item-content {
    font-size: 14px;
    color: #192236;
    font-weight: 500;
    // height: 20px;
    line-height: 20px;
    position: relative;
    bottom: 1px;
  }
}
:deep(.edit) {
  margin-top: -16px;
  padding: 0 8px;

  .ant-descriptions-item-label {
    justify-content: end;
    align-items: start;
    width: 114px;
    font-size: 12px;
    color: #192236;
    font-weight: 600;
  }
  .ant-descriptions-row > th {
    padding-bottom: 6px;
  }
  .ant-descriptions-row > td {
  }
  .ant-descriptions-item-content {
    font-size: 14px;
    color: #192236;
    font-weight: 500;
    height: 498px;
    line-height: 20px;
    position: relative;
    bottom: -4px;
  }
}
:deep(.preview) {
  .ant-descriptions-item-label {
    position: relative;
    top: 12px;
  }
}

.title {
  padding-left: 12px;
  padding-bottom: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: @text-color;
  line-height: 22px;
  position: relative;
  border-bottom: 1px solid #e8e8e8;
  &::before {
    content: '';
    width: 4px;
    height: 16px;
    background: @primary-color;
    border-radius: 2px;
    position: absolute;
    left: 0;
    top: 2px;
  }
}

.uploadLogo {
  margin: 24px 0;
  padding: 0 8px;
  &.uploadCustomer {
    padding: 0;
    margin: 0;
  }
  :deep(.ant-image-img) {
    background-color: #f3f4f8;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader {
    position: relative;
    .file-close {
      font-size: 12px;
      color: #c0c0c0;
      position: absolute;
      right: 2px;
      top: 0;
      cursor: pointer;
      z-index: 999;
    }
  }

  :deep(.ant-form-item-no-colon) {
    height: 38px;
    align-items: center;
  }
  // .avatar-uploader > .ant-upload {
  //   width: 240px;
  //   height: 38px;
  // }
  :deep(.ant-upload) {
    position: relative;
    width: auto;
    height: auto;
    .inner-info {
      width: 240px;
      height: 38px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    img {
      background-color: #f3f4f8;
    }
  }
  .ant-upload-select-picture-card i {
    font-size: 12px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-left: 5px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #535d71;
  }
  :deep(.ant-form-itm-no-colon) {
    width: 61px;
    height: 22px;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #192236;
    line-height: 22px;
  }
  :deep(.file-upload) {
    width: 242px;
    height: 40px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #cdcdcd;
  }
  .upload-info {
    color: #c0c0c0;
    font-size: 12px;
    .info-icon {
      font-size: 14px;
      margin-right: 4px;
    }
  }
}
.service {
  margin-top: 24px;
  padding: 0 8px;
  margin-bottom: 24px;
  .service-btn {
    display: flex;
    .btn-link {
      margin-left: 8px;
      &:focus {
        border-color: @primary-color;
        background: @primary-color;
      }
    }
  }
  :deep(.ant-input-affix-wrapper) {
    width: 408px;
  }
  :deep(.ant-form-item-control-input-content) {
    width: 408px;
  }
}
:deep(.ant-switch) {
  background-color: #c0c0c0;
}
.channel-custom {
  display: flex;
  align-items: center;
  // margin-top: 10px;
  padding: 0 8px;
  margin-bottom: 20px;
  color: #c0c0c0;
  font-size: 12px;
  &.channel-custom-invoice {
    padding: 0;
    margin-top: 0;
    margin-bottom: 24px;
  }
  .ant-switch-checked {
    background-color: #4aa353;
  }
  :deep(.ant-form-item) {
    margin-bottom: 0 !important;
  }
  .icon {
    position: relative;
    bottom: -1px;
    font-size: 12px;
    margin-right: 4px;
    margin-left: 10px;
  }
  .describe {
    width: 300px;
    height: 14px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #c0c0c0;
    line-height: 14px;
  }
}
.staticCode {
  position: relative;
  width: 436px;
  height: 498px;
  background-image: url('../../../../assets/images/staticCode.png');
  &.staticCodeView {
    margin-left: -8px;
  }
  .QRcode {
    width: 128px;
    height: 128px;
    left: 156px;
    top: 175px;
    position: absolute;
    background-image: url('../../../../assets/images/qrCode.png');
  }
  .slogan {
    position: absolute;
    text-align: center;
    left: 31px;
    bottom: 35px;
    width: 376px;
    height: 18px;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #2a64f6;
    line-height: 18px;
  }
  .contactInfo {
    position: absolute;
    left: 31px;
    bottom: 15px;
    width: 376px;
    text-align: center;
    height: 18px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #192236;
    line-height: 18px;
  }
}
</style>
